package com.wanmait.shoppingsys.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;



public class DbHelper {

	private static String url = "jdbc:mysql://127.0.0.1:3306/specialty_sys?useUnicode=true&characterEncoding=UTF-8";
	private static String user = "root";
	private static String pass = "aa253500";
	
	
	static {
		
		try {
			//Driver driver = new Driver();
			//DriverManager.registerDriver(driver);
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {	
			e.printStackTrace();
		}
	}
	
	
	public static Connection getConn()
	{
		try {
			Connection conn = DriverManager.getConnection(url,user,pass);
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	public static void close(ResultSet rs) {
		try {
			rs.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	
	public static void close(Statement ps) {
		
		try {
			ps.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	
	
	public static void close(Connection conn) {
		try {
			conn.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	public static void close(Statement ps,Connection conn) {
		close(ps);
		close(conn);
	}
	
	
	
	public static void close(ResultSet rs ,Statement ps,Connection conn) {
		close(rs);
		close(ps);
		close(conn);
	}
	
	
	
	public static void update(String sql,ArrayList params)
	{
		Connection conn = DbHelper.getConn();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			
			for(int i=0;params!=null&&i<params.size();i++) {
				ps.setObject(i+1, params.get(i));
			}
			
			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			DbHelper.close(ps, conn);
		}
	}
	
}
